const express = require('express');
const axios = require('axios');
const app = express();

app.use(require('cors')());

const router = express.Router();

router.get('/disc', (req, res) => {
    const url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg'
    axios.get(url, {
        headers: {
            referer: 'https://c.y.qq.com/',
            host: 'c.y.qq.com'
        },
        params: req.query
    }).then((response) => {
        res.json(response.data)
    }).catch((e) => {
        console.log(e)
    })
})

router.get('/getplaysongvkey', function (req, res) {
    const url = 'https://u.y.qq.com/cgi-bin/musicu.fcg'
    axios.get(url, {
        headers: {
        origin: 'https://y.qq.com',
        referer: 'https://y.qq.com/portal/player.html'
        },
        params: req.query
    }).then((response) => {
        res.json(response.data)
    }).catch((e)=>{
        console.log(e)
    })
})

router.get('/lyric', function (req, res) {
    var url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'

    axios.get(url, {
        headers: {
            referer: 'https://c.y.qq.com/',
            host: 'c.y.qq.com'
        },
        params: req.query
    }).then((response) => {
        var ret = response.data
        if (typeof ret === 'string') {
            var reg = /^\w+\(({[^()]+})\)$/
            var matches = ret.match(reg)
            if (matches) {
                ret = JSON.parse(matches[1])
            }
        }
        res.json(ret)
    }).catch((e) => {
        console.log(e)
    })
})

router.get('/getdiscdetail', (req, res) => {
    const url = 'https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg';

    axios.get(url, {
        headers: {
            referer: `https://y.qq.com/n/yqq/playlist/${req.query.disstid}.html`,
            host: 'c.y.qq.com'
        },
        params: req.query
    }).then(response => {
        let ret = response.data;
        if (typeof ret === 'string') {
            const reg = /^\w+\(({.+})\)$/;
            const matches = ret.match(reg);
            if (matches) {
                ret = JSON.parse(matches[1]);
            }
        }
        res.json(ret);
    }).catch(e => {
        console.log(e);
    })
})

router.get('/search', (req, res) => {
    const url = 'https://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp'

    axios.get(url, {
        headers: {
            referer: 'https://c.y.qq.com/',
            host: 'c.y.qq.com'
        },
        params: req.query
    }).then(resData => {
        res.json(resData.data);
    })
})

app.use('/api', router);
app.use(express.static(__dirname + '/public'));

app.listen(3000, () => {
    console.log('server is running');
})
